
#include "Router.h"
#include "CCLuaEngine.h"
#include "base_nodes/CCNode.h"
#include "tolua++.h"
#include "EditorScene.h"

#include "QErrorMessage"

#include "qttreepropertybrowser.h"
#include "qtvariantproperty.h"
#include "qtpropertybrowser.h"
#include "StringUtil.h"
#include "qevent.h"
#include "BoxList.h"
#include "qlist.h"
#include "Command.h"

USING_NS_CC;

SINGLETON_INSTANCE(Router);

void Router::addProp(const char* name, 
    const char* type, const char* value, const char* choices, bool readonly)
{
    _ignoreValueChange = true;
    emit onAddProp(name, type, value, choices, readonly);
    _ignoreValueChange = false;
}

void Router::setProp(const char* name, const char* value)
{
    _ignoreValueChange = true;
    emit onSetProp(name, value);
    _ignoreValueChange = false;
}

void Router::onValueChange(TreeItem* item, const QString& name, const QString& value)
{
    if (_ignoreValueChange)
        return;

    if (item)
        cmd_mgr::getInstance().add(new cmd_Prop(item->getWidget(), name, value));
}

void Router::clearProp()
{
    emit onClearProp();
}

static void callGlobal(const char* func, TreeItem* item)
{
    auto e = CCLuaEngine::defaultEngine();
    auto s = e->getLuaStack();

    tolua_pushusertype(s->getLuaState(), (void*)item, "TreeItem");
    e->executeGlobalFunction(func, 1);
}

void Router::onAddItem(TreeItem* item, const QString& name, const QString& type)
{
    auto e = CCLuaEngine::defaultEngine();
    auto s = e->getLuaStack();

    tolua_pushusertype(s->getLuaState(), (void*)item, "TreeItem");
    s->pushString(type.toUtf8());
    s->pushString(name.toUtf8());
    e->executeGlobalFunction("onAddItem", 3);
}

void Router::onSelectedItem(TreeItem* item)
{
    callGlobal("onSelectedItem", item);
}

void Router::throwError(const char* msg)
{
    QString errormsg(msg);
    errormsg.replace("\n", "<br/>");

    QErrorMessage* d = new QErrorMessage;
    d->setWindowModality(Qt::ApplicationModal);
    d->resize(QSize(600, 400));
    d->showMessage(errormsg);
}

